#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/msg.h>

#define MB (1024 * 1024)

void* my_alloc(int size) {
    void* ptr = malloc(size);
    if (!ptr) {
        fprintf(stderr, "malloc failed for %d bytes\n", size);
        exit(EXIT_FAILURE);
    }
    printf("Allocated %d MB, address: %p-%p\n", size / MB, ptr, ptr + size);
    return ptr;
}

void wait_for_enter() {
    int c;
    printf("Press Enter to continue...\n");
    while ((c = getchar()) != '\n' && c != EOF); // 清除缓冲区
}

int main() {
    pid_t pid = getpid();
    printf("Process PID: %d\n", pid);
    wait_for_enter();

    // Step 1: Allocate six 128MB blocks
    void* block1 = my_alloc(128 * MB);
    void* block2 = my_alloc(128 * MB);
    void* block3 = my_alloc(128 * MB);
    void* block4 = my_alloc(128 * MB);
    void* block5 = my_alloc(128 * MB);
    void* block6 = my_alloc(128 * MB);
    printf("Successfully allocated 6 memory blocks of 128MB.\n");
    wait_for_enter();

    // Step 2: Free #2, #3, #5
    free(block2);
    free(block3);
    free(block5);
    printf("Freed memory blocks 2, 3, and 5.\n");
    wait_for_enter();

    // Step 3: Allocate 1024MB block
    void* large_block = my_alloc(1024 * MB);
    wait_for_enter();

    // Step 4: Allocate 64MB block
    void* small_block = my_alloc(64 * MB);
    wait_for_enter();

    // Final cleanup
    free(block1);
    free(block4);
    free(block6);
    free(large_block);
    free(small_block);

    printf("All memory has been released.\n");
    return 0;
}